using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.IO;



namespace BackgroundRAR
{



    public partial class BackgroundUnRAR : Form
    {
        public int unrarStep;
        private string initDir, unrarExecutablePath;

        public BackgroundUnRAR(string[] args)
        {
            bool sourceFilePassed=false;
            InitializeComponent();
            for (int i = 0; i < 3; i++)
                SourceFile[i] = null;
            UnRARing = false;
            Paused = false;
            initDir = Directory.GetCurrentDirectory();
            unrarExecutablePath = Directory.GetParent(Directory.GetParent(initDir).FullName).FullName + @"\UnRAR.exe";
            //process arguments
            foreach (string s in args)
            {
                if (s.ToLower() == "-lowpriority")
                    LowPriority.Checked = true;
                else if (s.ToLower() == "-hybernate")
                    Hybernate.Checked = true;
                else if (ValidateFileName(s))
                {
                    if (Source1.Text == String.Empty)
                        Source1.Text = s;
                    else if (Source2.Text == String.Empty)
                        Source2.Text = s;
                    else if (Source3.Text == String.Empty)
                        Source3.Text = s;
                    sourceFilePassed = true;
                }
            }
            if (sourceFilePassed)
                Run_Click(this, null);
            
        }

        #region Click Event for the open buttons
        //Click event for the open buttons...
        private void Open3_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile3 = new OpenFileDialog();
            openFile3.Filter = "RAR files|*.rar||*.part01";
            openFile3.InitialDirectory = "D:\\movies\\";
            if (openFile3.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                Source3.Text = openFile3.FileName;
            if (openFile3.FileName != String.Empty)
                LogBox.AppendText("\n" + openFile3.FileName + " Opened" + "\n");
        }

        private void Open2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile2 = new OpenFileDialog();
            openFile2.Filter = "RAR files|*.rar||*.part01";
            openFile2.InitialDirectory = "D:\\movies\\";
            if (openFile2.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                Source2.Text = openFile2.FileName;
            if (openFile2.FileName != String.Empty)
                LogBox.AppendText("\n" + openFile2.FileName + " Opened" + "\n");
        }

        private void Open1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile1 = new OpenFileDialog();
            openFile1.Filter = "RAR files|*.rar||*.part01";
            openFile1.InitialDirectory = "D:\\movies\\";
            if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                Source1.Text = openFile1.FileName;
            if (openFile1.FileName != String.Empty)
                LogBox.AppendText("\n" + openFile1.FileName + " Opened" + "\n");
        }
        #endregion

        public string[] SourceFile = new string[3];
        public bool UnRARing;

        private void UnRAR(string str)
        {
            UnRARing = true;
            this.Text = "BackgroundUnRAR [UnRARing...]";
            string UnRARSource = str;
            string UnRARSourceDir = GetDir(str);
            Process processUnrar = new Process();
            ProcessStartInfo ps = processUnrar.StartInfo;
            ps.FileName = unrarExecutablePath;
            ps.Arguments = "e -o+" + " \"" + UnRARSource + "\" \"" + UnRARSourceDir + "\"";
            //  new ProcessStartInfo("D:\\UnRAR.exe","e -o+"+" \""+UnRARSource+"\" \""+UnRARSourceDir+"\"");
            ps.UseShellExecute = false;
            ps.RedirectStandardOutput = true;
            ps.CreateNoWindow = true;
            processUnrar.EnableRaisingEvents = true;
            processUnrar.Exited += new EventHandler(processUnrar_Exited);
            processUnrar.SynchronizingObject = LogBox;
            processUnrar.Start();
            if (!processUnrar.HasExited)
            {
                if (LowPriority.Checked)
                    processUnrar.PriorityClass = ProcessPriorityClass.BelowNormal;
                else if (Hybernate.Checked)
                    processUnrar.PriorityClass = ProcessPriorityClass.RealTime;
                else
                    processUnrar.PriorityClass = ProcessPriorityClass.Normal;
            }

        }

        private void processUnrar_Exited(object sender, EventArgs e)
        {
            UnRARing = false;
            LogBox.AppendText("\n" + SourceFile[unrarStep] + " unrar complete...\n");
            unrarStep++;
            UnRARManager();
        }


        private void AddSource()
        {
            int i = 0;
            if (Source1.Text != null)
            {
                SourceFile[i] = Source1.Text;
                i++;
            }
            if (Source2.Text != null)
            {
                SourceFile[i] = Source2.Text;
                i++;
            }
            if (Source3.Text != null)
            {
                SourceFile[i] = Source3.Text;
                i++;
            }
        }

        private void UnRARManager()
        {
            if (unrarStep == 3)
            {
                this.Text = "BackgroundUnRAR";
                ToggleEnable();
                if (Hybernate.Checked)
                    GoHybernate();
                return;
            }

            if (SourceFile[unrarStep] != String.Empty)
                UnRAR(SourceFile[unrarStep]);
            else
            {
                unrarStep++;
                UnRARManager();
            }

        }

        private void QueueUnRAR()
        {
            int i = 0;
            for (i = 0; i < 3; i++)
            {
                //validate again here...
                if (SourceFile[i] != String.Empty)
                    UnRAR(SourceFile[i]);
                while (UnRARing == true)
                {
                    Thread.Sleep(500);
                    this.Refresh();
                }
                if (SourceFile[i] != String.Empty)
                    LogBox.AppendText("\n" + SourceFile[i] + " unrar complete...\n");
            }
            this.Text = "BackgroundUnRAR";
            ToggleEnable();
            if (Hybernate.Checked)
                GoHybernate();

        }

        private string GetDir(String str)
        {
            //int i;

            if (str.LastIndexOf('\\') != -1)
                return str.Substring(0, str.LastIndexOf('\\'));
            else
                return null;
        }

        private void GoHybernate()
        {
            ProcessStartInfo ps = new ProcessStartInfo("C:\\windows\\system32\\rundll32.exe", "powrprof.dll,SetSuspendState");
            ps.UseShellExecute = false;
            ps.RedirectStandardOutput = true;
            ps.CreateNoWindow = true;
            Process p = Process.Start(ps);
            Application.Exit();

        }

        private void ToggleEnable()
        {
            Open1.Enabled = !Open1.Enabled;
            Open2.Enabled = !Open2.Enabled;
            Open3.Enabled = !Open3.Enabled;
            Source1.ReadOnly = !Source1.ReadOnly;
            Source2.ReadOnly = !Source2.ReadOnly;
            Source3.ReadOnly = !Source3.ReadOnly;
            Run.Enabled = !Run.Enabled;
        }

        private bool ValidateFileName()
        {
            for (int i = 0; i < 3; i++)
            {
                if (SourceFile[i] != String.Empty)
                    if (!System.IO.File.Exists(SourceFile[i]))
                    {
                        MessageBox.Show("Check File Name pls...");
                        return false;
                    }
                    else if (!IsRAR(SourceFile[i]))
                    {
                        MessageBox.Show("Check file type pls...");
                        return false;
                    }
            }
            return true;
        }

        private bool ValidateFileName(string s)
        {
            if (File.Exists(s)&&IsRAR(s))
                return true;
            else
                return false;
        }


        private void Run_Click(object sender, EventArgs e)
        {
            //Create Queue
            AddSource();
            unrarStep = 0;
            //Validate directory
            if (ValidateFileName() == false)
                return;
            //Disable commands
            ToggleEnable();
            //Start UnRAR
            //QueueUnRAR();
            UnRARManager();
        }

        Boolean Paused;

        private void PauseButtom_Click(object sender, EventArgs e)
        {
            if (!Paused)
            {
                //Get Process
                Process[] UnRARInstances = Process.GetProcessesByName("UnRAR");
                foreach (Process process in UnRARInstances)
                {
                    process.PriorityClass = ProcessPriorityClass.BelowNormal;
                }
                Paused = true;
                PauseButtom.Text = "Resume";
            }
            else
            {
                //Get Process
                Process[] UnRARInstances = Process.GetProcessesByName("UnRAR");
                foreach (Process process in UnRARInstances)
                {
                    process.PriorityClass = ProcessPriorityClass.Normal;
                }
                Paused = false;
                PauseButtom.Text = "Pause";
            }

        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.All;
            else
                e.Effect = DragDropEffects.None;
        }

        private bool IsRAR(string str)
        {
            string ext = str.Substring(str.Length - 3, 3).ToLower();

            if (ext == "rar")
                return true;
            else if (str.Substring(str.Length - 3, 3) == "r01")
                return true;
            else
                return false;
        }


        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            if (s.Length > 1)
                MessageBox.Show("Only the first file will be added...");
            if (!IsRAR(s[0]))
            {
                MessageBox.Show("Check file type pls...");
                return;
            }
            if (Source1.Text == String.Empty)
                Source1.Text = s[0];
            else if (Source2.Text == String.Empty)
                Source2.Text = s[0];
            else if (Source3.Text == String.Empty)
                Source3.Text = s[0];
            else
                return;
            LogBox.AppendText(s[0] + " Opened" + "\n");
        }

        private void Clear_Click(object sender, EventArgs e)
        {
            Source1.Text = String.Empty;
            Source2.Text = String.Empty;
            Source3.Text = String.Empty;

        }


        private void BackgroundUnRAR_KeyDown(object sender, KeyEventArgs e)
        {
            if (UnRARing)
                return;

            if (e.KeyCode == Keys.Escape)
                Application.Exit();

        }



    }
}